﻿using System;
using System.Threading.Tasks;

namespace HVACWebService.Common
{
    /// <summary>
    /// </summary>
    public static class ExceptionHelper
    {
        /// <summary>
        ///     Exes the try asynchronous.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fun">The fun.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static async Task<T> ExTryAsync<T>(Func<Task<T>> fun, string errorMessage)
        {
            try
            {
                return fun().Result;
            }
            catch (Exception)
            {
                throw new Exception(errorMessage);
            }
        }

        /// <summary>
        ///     Exes the try.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fun">The fun.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static T ExTry<T>(Func<T> fun, string errorMessage)
        {
            try
            {
                return fun();
            }
            catch (Exception e)
            {
                throw new Exception(errorMessage);
            }
        }

        /// <summary>
        ///     Exes the try.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fun">The fun.</param>
        /// <param name="defaultValue">The default value.</param>
        /// <returns></returns>
        public static T ExTry<T>(Func<T> fun, T defaultValue)
        {
            try
            {
                return fun();
            }
            catch (Exception)
            {
                return defaultValue;
            }
        }
    }
}